// index.js
import { 
  handleCommodityChange, 
  handleCommodityListChange,
  getOnCommodityNumberIsZero, 
  getNewShoppingCarData, 
  setNewShoppingCarData 
} from '../../utils/commodityOpt'; // 公共的操作方法

let cardListHeight = [0], 
shareCommodityCid = null; // 分享的商品cid
Page({
  data: {
    navHeight: 0,
    navTop: 0,
    storeTop: 0,
    scrollHeight:0,
    scrollHeights:0,//存储简约前的scrollHeights值
    sumHeight:0,
    sumHeights:0, //存储简约前的sumHeight值
    commodityWrapTop:0,
    commodityWrapTops:0, // 存储简约前的commodityWrapTops值
    commodityIsMini:false, //是否简约
    typeActive: 0, //左侧类型选中项
    comdtyN:'card',// 滚动标识
    comdtyId:'card',// 滚动到哪个card标识
    storeInfo:{
      stitle:'校园里的杂货铺',
      imageUrl:'/images/store_icon.jpeg',
      synopsis:'各种好吃的零食，欢迎来购买哦~~',
      latitude:23.7792386,
      longitude:109.2367614,
      path: '/page/index/index',
      infos:['18510770914','chinahhl1997','广西贵港平南县大新镇古文村新二屯36号(塱儿辽)']
    },
    shareInfo:{ // 分享信息
      title: '校园里的杂货铺',
      desc: '各种好吃的零食，欢迎来购买哦~~',
      path: '/page/index/index'
    }, 
    commodityInfo:[
      {
        typeId:0,
        typeName:'优惠价格',
        cdList:[
          {cid:1000, 
            specs: [
              { 
                typeId: '55454544', 
                typeTitle: '分量', 
                subList: [
                  { sid: '1545451546', sname: '大份' },
                  { sid: '1545451547', sname: '中份' },
                  { sid: '1545451548', sname: '小份' },
                ] 
              },
              { 
                typeId: '55454546', 
                typeTitle: '加量', 
                subList: [
                  { sid: '2545451546', sname: '鸡蛋' },
                  { sid: '3545451547', sname: '油条' },
                  { sid: '4545451548', sname: '莴笋' },
                ] 
              }
          ], 
            cName:'优惠辣条1',remain:100,dt:0,price:1.00,oPrice:1.00,imageUrl:'../../images/1.jpg'},// remain => 剩余
          {cid:1001, specs: [], cName:'优惠辣条2',remain:100,dt:8.81,price:1.00,oPrice:2.00,imageUrl:'../../images/2.jpg'},
          {cid:1002, specs: [], cName:'优惠辣条3',remain:100,dt:1.5,price:1.00,oPrice:1.8,imageUrl:'../../images/1.jpg'},
          {cid:1003, specs: [], cName:'优惠辣条4',remain:100,dt:0,price:1.00,oPrice:1.00,imageUrl:'../../images/2.jpg'},
          {cid:1004, specs: [], cName:'优惠辣条6',remain:100,dt:3.11,price:1.00,oPrice:10.00,imageUrl:'../../images/1.jpg'},
          {cid:1005, specs: [], cName:'优惠辣条7',remain:100,dt:3.21,price:1.00,oPrice:10.00,imageUrl:'../../images/1.jpg'},
          {cid:1006, specs: [], cName:'优惠辣条8',remain:100,dt:3.61,price:1.00,oPrice:10.00,imageUrl:'../../images/1.jpg'},
        ]
      },
      {
        typeId:1,
        typeName:'夏天小零食',
        cdList:[
          {cid:2000,cName:'辣条1',remain:100,dt:0,price:2.00,oPrice:2.00,imageUrl:'../../images/1.jpg'},
          {cid:2001,cName:'辣条2',remain:100,dt:6.9,price:3.20,oPrice:3.50,imageUrl:'../../images/1.jpg'},
          {cid:2002,cName:'辣条3',remain:100,dt:0,price:3.50,oPrice:3.50,imageUrl:'../../images/2.jpg'},
          {cid:2003,cName:'辣条4',remain:100,dt:7.2,price:2.00,oPrice:1.76,imageUrl:'../../images/1.jpg'}
        ]
      },
      {
        typeId:2,
        typeName:'夏天小零食2',
        cdList:[
          {cid:3000,cName:'辣条2',remain:100,dt:0,price:2.00,oPrice:2.00,imageUrl:'../../images/2.jpg'},
          {cid:3001,cName:'夏天小零食2',remain:100,dt:6.9,price:2.00,oPrice:2.00,imageUrl:'../../images/2.jpg'},
          {cid:3002,cName:'辣条4',remain:100,dt:0,price:2.00,oPrice:2.00,imageUrl:'../../images/2.jpg'},
          {cid:3003,cName:'夏天小零食2',remain:100,dt:7.2,price:2.00,oPrice:2.00,imageUrl:'../../images/2.jpg'}
        ]
      },
    ],
  },
  onShow(){
    
  },
  onReady() {
    this.storeDetails = this.selectComponent('#storeDetails');
    this.commodityInfo = this.selectComponent('#commodityInfo');
    this.spCart = this.selectComponent('#spCart');
    this.initMain();
    setTimeout(()=>{
      shareCommodityCid && this.tapCommitem(shareCommodityCid);// 处理从分享进入
    },200);
  },
  onLoad(e) {
    console.log("onLoad");
    this.initDeviceInfo(); // 必要设备参数
    this.initCommodityPayNumber(this.getListCommodityAllInfo()); // 初始化选购数量
    this.handleShare(e);// 是否从分享进入
  },
  initMain: async function(){
    await this.settCommodity_wrapTop();
    await this.settCommodityHeight();
    await this.settingScrollHeight();
    await this.handleItemsObjs();
    await this.initSelect();
  },
  // 初始化设备必要参数
  initDeviceInfo(){
    const systemInfo = wx.getSystemInfoSync(), // 获取系统信息
      menuButtonInfo = wx.getMenuButtonBoundingClientRect(), // 胶囊按钮位置信息
      sbarHeight = systemInfo.statusBarHeight
    const navHeight = (menuButtonInfo.top - sbarHeight) * 2 + menuButtonInfo.height;
    const storeTop = navHeight + sbarHeight;
    this.setData({navTop: sbarHeight,navHeight: navHeight,storeTop: storeTop});
  },
  // 商品组件传来的数据
  commitemEvent(e){// type=0 减少 type=1 增加 type=3 点击了商品主体
    const {cid, type} = e.detail;
    switch(type){
      case 0: // 减少
        this.handleAddOrReduce(cid, 0); // 减少
        break;
      case 1: // 增加
        this.handleAddOrReduce(cid, 1); // 添加
        break;
      default: // 点击商品主体
        this.tapCommitem(cid); // 商品主体
        break
    }
    this.verifyHideCart()

  },
  // 从分享进入
  handleShare(pObj){
    if(!pObj || Object.keys(pObj).length==0||!'cid' in pObj){return}
    shareCommodityCid = pObj.cid;
  }, 
  // 点击某个商品商品
  tapCommitem(cid){
    const obj = this.getCommodityInfo(cid);
    this.commodityInfo.setCommodityInfo(obj.cItemInfo,0);
  },
  // 处理选中的商品添加或者减少数量 组件绑定调用
  handleAddOrReduce(cid, type){ 
    return this.handlePayCommOdityNumber(cid, type);
  },
  // 处理选好的了操作, 跳转确认订单页面
  handleSelectSuccess(comms){
    let commOrderInfo = [];
    for(let i in comms){
      const temp = {
        cid:comms[i].cid,
        payNumber:comms[i].payNumber
      };
      commOrderInfo.push(temp);
    }
    console.log(commOrderInfo);
    this.toPages(2, commOrderInfo);
  },
  // 购物车组件的商品变动|选好了的操作
  quantityChange(o){
    console.log('---->下单页触发-购物车组件的商品变动', o)
    const type = o.detail.type;
    if(type===0||type===1){
      const cid = o.detail.cid;
      const list = handleCommodityListChange(this.getListCommodityAllInfo(), cid, type, false);
      return this.setData({ commodityInfo: list });
    }else if(type == 3){ 
      this.clearAllCommodityNumber();// 清空
    }else if(type == 5){ // 获取选好了的商品数据
      this.handleSelectSuccess(o.detail.comms);
    }
  },
  // 单个商品变动
  settingCommodityNumber(e){
    const {cid, payNumber} = e.detail;
    this.handleCommodityChange(cid, payNumber); // 更改下单页商品数量
    const { cItemInfo } = this.getCommodityInfo(cid); // 拿到该商品信息
    this.setCartCommodityData(cItemInfo, 2); // 更改指定数量
  },
  // 处理商品数量信息变动
  handleCommodityChange(cid, number){
    let cInfo = this.getListCommodityAllInfo(), isChange = false;
    for(let i in cInfo){
      let cdList = cInfo[i].cdList;
      for(let x in cdList){
        if(cdList[x].cid == cid){
          cdList[x].payNumber = number;
          isChange = true;
          break;
        }
      }
    }
    if(!isChange){return}
    this.setData({commodityInfo:cInfo});
  },
  // 清空已选所有商品数量
  clearAllCommodityNumber(){
    let cInfoList = this.getListCommodityAllInfo();
    for(let i in cInfoList){
      let cdList = cInfoList[i].cdList;
      for(let x in cdList){
        if(cdList[x].payNumber != 0){
          cdList[x].payNumber = 0;
        }
      }
    }
    this.setData({commodityInfo:cInfoList}); // 清空已选择商品数操作
  },
  // 处理商品选购数量
  handlePayCommOdityNumber(cid, type){// type: 0=>删除 1=>添加 2=>清空
    const { cItemInfo } = this.getCommodityInfo(cid);
    const newCarList = getNewShoppingCarData(); // 获取全局管理状态里的最新购物车商品数据
    const carList = handleCommodityChange(newCarList, cItemInfo, type, void 0, true); // 操作购物车里的数据
    setNewShoppingCarData(carList); // 更新购物车数据
    const cList = handleCommodityListChange(this.getListCommodityAllInfo(), cItemInfo.cid, type);
    this.setData({commodityInfo: cList});
  },
  // 更新全局状态里的最新购物车数据
  setCartCommodityData(cItem, type){
    const newCarList = getNewShoppingCarData(); // 获取全局管理状态里的最新购物车商品数据
    const cList = handleCommodityChange(newCarList, cItem, type, cItem.payNumber); // 处理变动商品
    setNewShoppingCarData(cList); // 更新购物车数据
  },
  // 获得某个商品的信息
  getCommodityInfo(cid){
    const cInfo = JSON.parse(JSON.stringify(this.getListCommodityAllInfo()));
    let cItemInfo = {};
    for(var i in cInfo){
      const cdList = cInfo[i].cdList;
      for(var x in cdList){
        if(cdList[x].cid == cid){
          cItemInfo = cdList[x];
          break
        }
      }
      if(Object.keys(cItemInfo).length != 0){
        break;
      }
    }
    if(Object.keys(cItemInfo).length==0){
      console.log('未找到该商品cid',cid);
    }
    return {cItemInfo:cItemInfo,cInfo:cInfo};
  },
  // 初始化选购数量
  initCommodityPayNumber(clist){
    let cInfo = clist;
    for(var i in cInfo){
      const cdList = cInfo[i].cdList;
      for(var x in cdList){
        cdList[x].payNumber = 0;
      }
    }
    this.setData({commodityInfo:cInfo})
  },
  // 分享信息设置
  settingShareInfo(e){
    let {pObj,type} = e.detail;
    if(type == 0){ // 还原分享设置
      return this.setData({shareInfo:pObj});
    }
    const shareInfo = this.data.shareInfo;
    this.commodityInfo.backupsShareInfos(shareInfo);
    this.setData({shareInfo: pObj});
  },
  // 获取所有商品的信息
  getListCommodityAllInfo(){
    return this.data.commodityInfo;
  },
  settCommodity_wrapTop: async function(){
    const storeHeight = await this.getVheight('.wrap_store');
    this.setData({commodityWrapTop:(this.getTopAllHeight()+storeHeight)+20});
  },
  getTopAllHeight(){
    const sbarHeight = this.data.navTop, // 状态高度
    navHeight = this.data.navHeight;
    return sbarHeight + navHeight;
  },
  bindScroll:async function(e){
    const st = e.detail.scrollTop;
    let selctIdx = 0;
    for(let i=0;i<cardListHeight.length;i++){
      if(cardListHeight[i+1]){
        if(st >= cardListHeight[i] && st < cardListHeight[i+1]){
          selctIdx = i;
          break;
        }
      }
    }
    const commodityIsMini = this.data.commodityIsMini; // 是否开启了简约
    if(st >= 100 && !commodityIsMini){ // 开启简约
      const cwTop = this.getTopAllHeight()+10, 
      screenHeight = wx.getSystemInfoSync().screenHeight,
      sumHeight = this.data.sumHeight,
      scrollHeight = this.data.scrollHeight,
      commodityWrapTop = this.data.commodityWrapTop;
      this.setData({
        commodityIsMini:true,
        sumHeights:sumHeight,
        commodityWrapTops:commodityWrapTop,
        commodityWrapTop:cwTop,
        sumHeight:screenHeight - cwTop,
        scrollHeights:scrollHeight,
      });
      this.settingScrollHeight();
    }else if(commodityIsMini && st < 100){
      const sumHeights = this.data.sumHeights,
      commodityWrapTops = this.data.commodityWrapTops,
      scrollHeights = this.data.scrollHeights;
      this.setData({
        commodityIsMini:false,
        sumHeight:sumHeights,
        commodityWrapTop:commodityWrapTops,
        scrollHeight:scrollHeights,
      });
    }
    let typeActive = this.data.typeActive;
    if(typeActive==selctIdx){return}
    this.setData({typeActive:selctIdx});
  },
  bindTapType(e){
    const idx = e.target.dataset.index,
    comdtyN = this.data.comdtyN;
    this.setData({typeActive: idx,comdtyId:comdtyN+idx});
  },
  // 更新列表选购数据-子组件调用【search】
  updateCommodityListData() {
    const list = getNewShoppingCarData()
    // 先把列表的购数量变0
    this.initCommodityPayNumber(this.getListCommodityAllInfo())
    // 再根据搜索传回的数据再重新加购
    for(const item of list) {
      this.handleCommodityChange(item.cid, item.payNumber)
    }
    this.verifyHideCart()
  },
  // 判断隐藏购物车
  verifyHideCart() {
    // 隐藏购物车
    if (getOnCommodityNumberIsZero()) {
      return this.spCart && this.spCart.hideCart()
    }
  },
  // 点击商铺信息触发
  storeInfoTapCallback(){
    this.storeDetails.showSds(this.data.storeInfo); // 传需要的信息
  },
  // 跳转其他页面 0=> 我的订单 1=> 搜索商品
  toJumpOtherView(e){
    const jumpType = e.currentTarget.dataset.jumptype;
    this.toPages(jumpType, this.data.storeInfo);
  },
  // 跳转其他页面具体实现方法
  toPages(jumpType, d){
    let path = '/pages/',param;
    d?param=JSON.stringify(d):param='';
    if(jumpType == 0){
      path += `orders/orders?storeInfo=${param}`;
    }else if(jumpType == 1){
      path += `search/search`;
    }else if(jumpType == 2){ // 跳转确认订单页面
      path += `corder/corder?comms=${param}`;
    }
    wx.navigateTo({url: path}); // 开始跳转
  },
  initSelect(){
    this.setData({comdtyId:this.data.comdtyId+this.data.typeActive});
  },
  handleItemsObjs:async function(){
    cardListHeight = [0];// 清空数组
    const cardListObj = await this.getvTops('.cardList');
    cardListObj.forEach(item => {
      const h = item.height + cardListHeight[cardListHeight.length-1];
      cardListHeight.push(h);
    });
  },
  settCommodityHeight: function(){
    const sHeight = wx.getSystemInfoSync().screenHeight;
    const sumHeight = sHeight - this.data.commodityWrapTop;
    this.setData({sumHeight:sumHeight});
  },
  settingScrollHeight: async function(){
    let height = await this.getVheight('.commodity_content');
    this.setData({scrollHeight: height});
  },
  getvTops(cName){
    const self = this;
    return new Promise((result,error)=>{
      self.getvObjs(cName,(o)=>{
        result(o);
      });
    });
  },
  getVheight(cName){
    const self = this;
    return new Promise((result,error)=>{
      self.getvObj(cName,(o)=>{
        result(o.height);
      });
    });
  },
  getvMarginTop(cName){
    const self = this;
    return new Promise((result,error)=>{
      self.getvObj(cName,(o)=>{
        result(o.top);
      });
    });
  },
  // 获取单个
  getvObj(cName,callback){
    wx.nextTick(() => {
      const query = wx.createSelectorQuery().in(this);
      query.select(cName)
        .boundingClientRect((rect) => {
          callback(rect);
        }).exec();
    });
  },
  // 获取多个
  getvObjs(cName,callback){
    wx.nextTick(() => {
      const query = wx.createSelectorQuery().in(this);
      query.selectAll(cName)
        .boundingClientRect((rect) => {
          callback(rect);
        }).exec();
    });
  },
  // 转发分享微信朋友
  onShareAppMessage:function () {
    wx.showShareMenu({
       withShareTicket: true,
       menus: [ 'shareTimeline']
    });
    return this.data.shareInfo;
  },
  // 分享朋友圈
  onShareTimeline: function () {
    const shareInfo = this.data.shareInfo;
      return {
        title: shareInfo.title,
        query: {
        },
        imageUrl: shareInfo.imageUrl  //分享图,默认小程序的logo
     }
  },
});
